/**
 * @description 读取excel
 * @param file File
 * @return 读取json
 *
 * 使用示例
 * import { getExcelData } from '@/utils/excel'
 * const data = await getExcelData(file)
 *   if (data.length === 0) {
 *     msgUtil.$message.error('此Excel表中无数据')
 *     return
 *   }
 *
 * */
import * as XLSX from 'xlsx'

// 定义 Excel 数据行的类型
export interface ExcelRow {
  [key: string]: string | number | boolean | Date
}

export function getExcelData(file: File): Promise<ExcelRow[]> {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.readAsArrayBuffer(file)
    reader.onload = function () {
      const buffer = reader.result as ArrayBuffer
      const bytes = new Uint8Array(buffer)
      const length = bytes.byteLength
      let binary = ''
      for (let i = 0; i < length; i++) {
        binary += String.fromCharCode(bytes[i])
      }
      const wb = XLSX.read(binary, {
        type: 'binary',
        cellDates: true,
      })
      const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) as ExcelRow[]
      resolve(outdata)
    }
  })
}
